import 'package:flower/utils/my_colors.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import '../../../../components/cached_image_widget.dart';
import '../../../../config/service_url.dart';
import '../../../../model/category_model.dart';
import '../../../../model/flower_list.dart';
import '../../../../utils/http_util.dart';
import '../../detail/flower_detail.dart';

/*分类*/
class Category extends StatefulWidget {
  final int? cid;
  const Category({super.key, this.cid});

  @override
  State<Category> createState() => _Category();
}

class _Category extends State<Category> with SingleTickerProviderStateMixin {
  List<CategoryData> categoryStatus = [];
  List<List<FlowerData>> flowerList = [];
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    queryCategoryList();
  }

  //获取分类的数据
  void queryCategoryList() async {
    Response result = await HttpUtil.get(getAllType);
    CategoryModel categoryModel = CategoryModel.fromJson(result.data);

    setState(() {
      categoryStatus = categoryModel.data!;
      flowerList = List.generate(categoryStatus.length, (_) => []);
      _tabController = TabController(length: categoryStatus.length, vsync: this);
      fetchFlowersForCategories();
    });
  }

  // 获取每个分类下的花列表
  void fetchFlowersForCategories() async {
    for (int i = 0; i < categoryStatus.length; i++) {
      final category = categoryStatus[i];
      Response result = await HttpUtil.get(getFlowerByType, queryParameters: {'tid': category.id});
      FlowerListModel flowerListModel = FlowerListModel.fromJson(result.data);
      setState(() {
        flowerList[i] = flowerListModel.data!;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: categoryStatus.length,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('全部分类'),
          centerTitle: true,
          bottom: categoryStatus.isEmpty ? null : TabBar(
            controller: _tabController,
            isScrollable: true,
            indicatorColor: MyColors.yellow,
            labelColor: MyColors.boyPink,
            tabs: categoryStatus.map((status) => Tab(text: status.name)).toList(),
          ),
        ),
        body: categoryStatus.isEmpty
            ? const Center(child: CircularProgressIndicator())
            : TabBarView(
          controller: _tabController,
          children: categoryStatus.asMap().entries.map((entry) {
            int index = entry.key;
            return CategoryListInfo(
              status: entry.value,
              flowerList: flowerList[index],
            );
          }).toList(),
        ),
      ),
    );
  }
}

class CategoryListInfo extends StatelessWidget {
  final CategoryData status;
  final List<FlowerData> flowerList;

  const CategoryListInfo({
    super.key,
    required this.status,
    required this.flowerList,
  });

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      padding: const EdgeInsets.all(10),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 10.0,
        mainAxisSpacing: 10.0,
        childAspectRatio: 0.75,
      ),
      itemCount: flowerList.length,
      itemBuilder: (context, index) {
        final flower = flowerList[index];
        return GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => FlowerDetailPage(flowerId: flower.id),
              ),
            );
          },
          child: Card(
            elevation: 3,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: ClipRRect(
                    borderRadius: const BorderRadius.vertical(top: Radius.circular(10)),
                    child: CachedImageWidget(
                      double.infinity,
                      double.infinity,
                      flower.coverUrl,
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        flower.name,
                        style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(height: 5),
                      Text(
                        flower.ename,
                        style: const TextStyle(
                          fontSize: 14,
                          color: MyColors.ename,
                        ),
                      ),
                      const SizedBox(height: 5),
                      Text(
                        "￥${flower.price}",
                        style: const TextStyle(
                          fontSize: 14,
                          color: MyColors.red,
                        ),
                      ),
                      const SizedBox(height: 5),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
